<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Mihail Merkov
 * Date: 13-9-2
 * Time: 20:58
 * To change this template use File | Settings | File Templates.
 */

namespace TennisTournament\Controller;

use TennisTournament\Helpers\ModelFactoriesHelper;
use TennisTournament\Model\Security;
use TennisTournament\Service\AuthenticationService;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Session\Container;
use Zend\View\Model\ViewModel;

class AuthenticationController extends AbstractActionController {

    /** @var AuthenticationService */
    private $authenticationService;

    const FORWARD_SHOW = 'tennis-tournament/authentication/show';

    public function __construct(AuthenticationService $authenticationService) {
        $this->authenticationService = $authenticationService;
    }

    public function showAction() {
        $allAuthenticatedUsers = $this->authenticationService->fetchAll();
        $params = array();

        if ($allAuthenticatedUsers == null || count($allAuthenticatedUsers) == 0) {
            $params["isRegistred"] = false;
        } else {
            $params["isRegistred"] = true;
        }

        $viewModel = new ViewModel();
        $viewModel->setTemplate(self::FORWARD_SHOW);
        return $viewModel->setVariables($params);
    }

    public function signUpAction() {
        $username = $this->params()->fromPost('username');
        $password = $this->params()->fromPost('password');

        $security = ModelFactoriesHelper::createSecurity(null, $username, $password, Security::ADMIN);
        $this->authenticationService->save($security);

        return $this->redirect()->toRoute('authentication', array('action', 'show'));
    }

    public function loginAction() {
        $username = $this->params()->fromPost('username');
        $password = $this->params()->fromPost('password');

        /** @var $security Security */
        $security = $this->authenticationService->getBy($username, $password);
        if ($security != null) {
            $sessionContainer = new Container('ROLES');
            $sessionContainer->offsetSet('ROLE', $security->getRole());
            return $this->redirect()->toRoute('home');
        }

        $errorsContainer = new Container('ERRORS');
        $errorsContainer->offsetSet('error_authentication', 'Wrong username or password');
        return $this->redirect()->toRoute('authentication');
    }
}